package com.example.medical_delivery_system.service.impl;

import com.example.medical_delivery_system.api.param.SaveCartItemParam;
import com.example.medical_delivery_system.api.param.UpdateCartItemParam;
import com.example.medical_delivery_system.api.vo.CartVO;
import com.example.medical_delivery_system.common.Exception;
import com.example.medical_delivery_system.common.Constants;
import com.example.medical_delivery_system.common.ServiceResultEnum;
import com.example.medical_delivery_system.dao.CartMapper;
import com.example.medical_delivery_system.dao.ProductMapper;
import com.example.medical_delivery_system.entity.Cart;
import com.example.medical_delivery_system.entity.Product;
import com.example.medical_delivery_system.service.CartService;
import com.example.medical_delivery_system.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public String saveCartItem(SaveCartItemParam saveCartItemParam, Long userId) {
        Cart temp = cartMapper.selectByUserIdAndGoodsId(userId, saveCartItemParam.getProductId());
        if (temp != null) {
            //已存在则修改该记录
            Exception.fail(ServiceResultEnum.SHOPPING_CART_ITEM_EXIST_ERROR.getResult());
        }
        Product product = productMapper.selectByPrimaryKey(saveCartItemParam.getProductId());
        //商品为空
        if (product == null) {
            return ServiceResultEnum.GOODS_NOT_EXIST.getResult();
        }

        Cart cart = new Cart();
        BeanUtil.copyProperties(saveCartItemParam, cart);
        cart.setUserId(userId);
        //保存记录
        if (cartMapper.insertSelective(cart) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public String updateCartItem(UpdateCartItemParam updateCartItemParam, Long userId) {
        Cart cartUpdate = cartMapper.selectByPrimaryKey(updateCartItemParam.getCartId());
        if (cartUpdate == null) {
            return ServiceResultEnum.DATA_NOT_EXIST.getResult();
        }
        if (!cartUpdate.getUserId().equals(userId)) {
            Exception.fail(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
        }

        //当前登录账号的userId与待修改的cartItem中userId不同，返回错误
        if (!cartUpdate.getUserId().equals(userId)) {
            return ServiceResultEnum.NO_PERMISSION_ERROR.getResult();
        }

        cartUpdate.setAmount(updateCartItemParam.getAmount());
        //修改记录
        if (cartMapper.updateByPrimaryKeySelective(cartUpdate) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }



    @Override
    public Boolean deleteById(Long cartItemId, Long userId) {
        Cart cart = cartMapper.selectByPrimaryKey(cartItemId);
        if (cart == null) {
            return false;
        }
        //userId不同不能删除
        if (!userId.equals(cart.getUserId())) {
            return false;
        }
        return cartMapper.deleteByPrimaryKey(cartItemId) > 0;
    }

    @Override
    public List<CartVO> getCartItemsForSettle(List<Long> cartItemIds, Long userId) {
        List<CartVO> cartVOS = new ArrayList<>();
        if (CollectionUtils.isEmpty(cartItemIds)) {
            Exception.fail("购物项不能为空");
        }
        List<Cart> carts = cartMapper.selectByUserIdAndCartItemIds(userId, cartItemIds);
        if (CollectionUtils.isEmpty(carts)) {
            Exception.fail("购物项不能为空");
        }
        if (carts.size() != cartItemIds.size()) {
            Exception.fail("参数异常");
        }
        return getCartItemVOS(cartVOS, carts);
    }

    @Override
    public List<CartVO> getCartItems(Long userId) {
        List<CartVO> cartVOS = new ArrayList<>();
        List<Cart> carts = cartMapper.selectByUserId(userId, Constants.SHOPPING_CART_ITEM_TOTAL_NUMBER);
        return getCartItemVOS(cartVOS, carts);
    }



    /**
     * 数据转换
     *
     * @param cartVOS
     * @param carts
     * @return
     */
    private List<CartVO> getCartItemVOS(List<CartVO> cartVOS, List<Cart> carts) {
        if (!CollectionUtils.isEmpty(carts)) {
            //查询商品信息并做数据转换
            List<Long> goodsIds = carts.stream().map(Cart::getProductId).collect(Collectors.toList());
            List<Product> goods = productMapper.selectByPrimaryKeys(goodsIds);
            Map<Long, Product> goodsMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(goods)) {
                goodsMap = goods.stream().collect(Collectors.toMap(Product::getProductId, Function.identity(), (entity1, entity2) -> entity1));
            }
            for (Cart cart : carts) {
                CartVO cartVO = new CartVO();
                BeanUtil.copyProperties(cart, cartVO);
                if (goodsMap.containsKey(cart.getProductId())) {
                    Product productTemp = goodsMap.get(cart.getProductId());
                    String goodsName = productTemp.getProductName();
                    // 字符串过长导致文字超出的问题
                    if (goodsName.length() > 28) {
                        goodsName = goodsName.substring(0, 28) + "...";
                    }
                    cartVO.setProductName(goodsName);
                    cartVOS.add(cartVO);
                }
            }
        }
        return cartVOS;
    }

    @Override
    public Cart getCartItemById(Long cartItemId) {
        Cart cart = cartMapper.selectByPrimaryKey(cartItemId);
        if (cart == null) {
            Exception.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        return cart;
    }




}
